package com.study.concurrentprogramming.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description :
 * @Author : guxuemin
 * @Version : V1.0.0
 * @Date : 2022/5/15 15:51
 */
public class SpinLock {
    private AtomicReference<Thread> owner = new AtomicReference<>();



    public void lock() {
        Thread thread = Thread.currentThread();
        while (!owner.compareAndSet(null, thread)) {
        }
    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        while (!owner.compareAndSet(thread, null)) {
        }
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        new Thread(() -> {
            spinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("release lock");
            spinLock.unlock();
        }, "t1").start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t2 take lock");
            spinLock.lock();
            System.out.println("t2 release lock");
            spinLock.unlock();
        },"t2").start();
    }
}
